<?php
class o2o_inventory_import {

    function run(&$cursor_id,$params){
        /*
         * 新增明细表中的数据
         * csv中填写的是 accounts_num线上账面数 和 accounts_share_num共享账面数
         * store线上实际数  share_store共享实际数 从sdb_o2o_product_store表中拿
         * 获取inventory_items明细表中 盈亏公式：short_over线上盘盈亏 = accounts_num - store ; share_short_over共享盘盈亏 = accounts_share_num - share_store ;
         */
        
        $mdlO2oProductStore = app::get('o2o')->model('product_store');
        $mdlO2oInventoryItems = app::get('o2o')->model('inventory_items');
        
        //统一获 store线上实际数  share_store共享实际数
        $bm_ids = array();
        foreach ($params["sdfdata"]["products"] as $var_product){
            $bm_ids[] = $var_product["bm_id"];
        }
        $rs_product_store = $mdlO2oProductStore->getList("bm_id,store,share_store",array("branch_id"=>$params["sdfdata"]["branch_id"],"bm_id|in"=>$bm_ids));
        $rl_bm_id_store = array();
        //当前门店仓关联的物料首次盘点 没有此记录 后续insert一条store=0 share_store=0的记录
        if(!empty($rs_product_store)){
            foreach ($rs_product_store as $var_product_store){
                $rl_bm_id_store[$var_product_store["bm_id"]] = array(
                        "store" => $var_product_store["store"],
                        "share_store" => $var_product_store["share_store"],
                );
            }
        }
        //新增明细表中的数据
        foreach ($params["sdfdata"]["products"] as $var_p){
            $accounts_num = intval($var_p["accounts_num"]);
            $accounts_share_num = intval($var_p["accounts_share_num"]);
            if(isset($rl_bm_id_store[$var_p["bm_id"]])){
                $store = intval($rl_bm_id_store[$var_p["bm_id"]]["store"]);
                $share_store = intval($rl_bm_id_store[$var_p["bm_id"]]["share_store"]);
            }else{
                //首次盘点 没有相关的库存记录 新建
                $store_insert_arr = array(
                    "branch_id" => $params["sdfdata"]["branch_id"],
                    "bm_id" => $var_p["bm_id"],
                );
                $mdlO2oProductStore->insert($store_insert_arr);
                $store = 0;
                $share_store = 0;
            }
            $short_over = $accounts_num - $store;
            $share_short_over = $accounts_share_num - $share_store;
            $insert_arr = array(
                "inventory_id" => $params["sdfdata"]["inv_id"],                
                "bm_id" => $var_p["bm_id"],                
                "accounts_num" => $accounts_num,                
                "accounts_share_num" => $accounts_share_num,                
                "actual_num" => $store,                
                "actual_share_num" => $share_store,                
                "short_over" => $short_over,
                "share_short_over" => $share_short_over,                
            );
            $mdlO2oInventoryItems->insert($insert_arr);
        }
        
        return false;
    }
}
